package com.wms.gateway.config;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;


@Primary
@Component
public class SwaggerProvider implements SwaggerResourcesProvider {
	
    /**
     * swagger2默认的url后缀
     */
    private static final String SWAGGER_URL = "/v2/api-docs";

    /**
     * 网关路由
     */
    @Autowired
    private RouteLocator routeLocator;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String self;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        Set<String> dealed = new HashSet<>();
        // 获取所有可用的host：serviceId
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
	        .filter(route -> !self.equals(route.getUri().getHost()))
	        .subscribe(route -> {
	        	URI uri = route.getUri();
	        	String scheme=uri.getScheme();
	        	String url  = uri.toString();
	        	String rescourceUrl;
	        	String resourceName;
	        	if(scheme.equalsIgnoreCase("lb")) {
	        		rescourceUrl = "/" + uri.getHost()+SWAGGER_URL;
	        		resourceName = uri.getHost();
	        	} else {
	        		rescourceUrl = "/" + route.getId()+SWAGGER_URL;
	        		resourceName = route.getId();
	        	}
	            if (!dealed.contains(url)) {
	                dealed.add(url);
	                SwaggerResource swaggerResource = new SwaggerResource();
	                swaggerResource.setName(resourceName);
	                swaggerResource.setSwaggerVersion("2.0");
	                swaggerResource.setUrl(rescourceUrl);
	                resources.add(swaggerResource);
	            }
	        });
        return resources;
    }
}